package cn.picclife.mwx.manager.sys.task;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import cn.picclife.mwx.manager.sys.mapper.ArchiveMapper;
import cn.picclife.mwx.manager.sys.mapper.CollectHtmlVideoMapper;
import cn.picclife.mwx.manager.sys.mapper.DataCollectMapper;
import cn.picclife.mwx.manager.sys.model.po.CollectHtmlVideo;
import cn.picclife.mwx.manager.sys.model.po.DataCollect;
import cn.picclife.mwx.manager.sys.service.CollectDataService;
import cn.picclife.mwx.manager.util.DateUtil;
import cn.picclife.mwx.manager.util.DateUtil.DateType;
import cn.picclife.mwx.manager.util.RedisUtil;

import com.alibaba.fastjson.JSON;

@Component
public class TimerTask {

	private static final Log log = LogFactory.getLog(TimerTask.class);

	@Autowired
	private ArchiveMapper mapper;
	@Autowired
	private DataCollectMapper dataMapper;
	@Resource(name = "redisCache")
	private RedisUtil redisUtil;
	@Autowired
	private CollectDataService collectDataServiceImpl;
	@Autowired
	private DataCollectMapper dataCollectMapper;
	@Autowired
	private CollectHtmlVideoMapper collectHtmlVideoMapper;

	//@Value("${file.filedir}")
	//private String fileDir;
//	private String fileDir ="/data/hsxtdata/data/video/";
	private String fileDir ="/data/work/appdata/video/";

	// @Scheduled(cron = "0 0 1 * * ?") // 每天1点触发
	// @Scheduled(cron = "*/15 * * * * ?") // 每隔15秒执行一次
	public void updateDataCollect() {
		log.info("----定时任务开始执行-----");
		// 获取清除的数据设置时间
		String time = mapper.queryAllData().get(0).getArchiveTime();
		Date date = DateUtil.addDate(new Date(), DateType.DAY,
				-Integer.valueOf(time));
		// 查找要清除的数据
		List<DataCollect> list = dataMapper.queryTaskList(date);
		// 清除数据更新为无效
		dataMapper.updateDataByArchiveTime("0", date);
		// 删除要清除的文件
		for (DataCollect dataCollect : list) {
			File file = new File(dataCollect.getUploadUrl());
			file.delete();
		}
		log.info("----定时任务执行结束-----");
	}

	//@Scheduled(cron = "0 */3 * * * ?")
	/*public void updateFileCollect() {

		log.info("--定时从redis中读取视频数据写入磁盘文件开始--");
		Set<String> keys = redisUtil.Keys("v2"+"video*");
		if (keys == null || keys.size() <= 0) {
			log.info("--没有视频数据，定时器退出--");
			log.info("--定时从redis中读取视频数据写入磁盘文件结束--");
			return;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		for (String key : keys) {
			//若当前时间戳减去redis中存放的最大时间戳小于5分钟则不下载 begin
			Set<ZSetOperations.TypedTuple<String>> scoreSet = redisUtil.rangeWithScores(key);
			List<ZSetOperations.TypedTuple<String>> scorelist = new ArrayList<ZSetOperations.TypedTuple<String>>(scoreSet);
			ZSetOperations.TypedTuple<String> score = scorelist.get(scorelist.size()-1);
			//=======================修改5分钟bug添加的日志
			log.info("--5minutes--系统时间："+Calendar.getInstance().getTimeInMillis());
			log.info("--5minutes--score.getScore():"+score.getScore());
			log.info("--5minutes--时间差:"+(Calendar.getInstance().getTimeInMillis()-score.getScore()));
			log.info("--5minutes--if判断:"+((Calendar.getInstance().getTimeInMillis()-score.getScore())<5*60*1000));
			//=======================修改5分钟bug添加的日志
			if((Calendar.getInstance().getTimeInMillis()-score.getScore())<5*60*1000) continue;
			//若当前时间戳减去redis中存放的最大时间戳小于5分钟则不下载 end
			Set<String> set = this.redisUtil.getZset(key);
			redisUtil.delete(key);// 删除redis缓存
			if (set == null || set.size() == 0) {
				continue;
			}
			log.info("视频uuid: " + key);
			String id = key.replace("v2video", "");
			DataCollect dataCollect = dataCollectMapper.queryDataById(id);
			String nowDateStr = "";
			if (dataCollect != null && dataCollect.getUploadTime() != null) {
				nowDateStr = sdf.format(dataCollect.getUploadTime());
			} else {
				nowDateStr = sdf.format(new Date());
			}
			Iterator<String> it = set.iterator();
			String str = "";
			StringBuffer data = new StringBuffer();
			String filePath = fileDir;
			while (it.hasNext()) {
				str = it.next();
				List<String> list1 = JSON.parseArray(str, String.class);
				for (String string : list1)
					data.append(string).append("\n");
			}
			filePath = String.valueOf(filePath) + nowDateStr.substring(0, 4)
					+ "/" + nowDateStr.substring(4, 6) + "/"
					+ nowDateStr.substring(6, 8) + "/" + dataCollect.getId()
					+ "/";
			File filep = new File(filePath);
			if (!filep.exists())
				filep.mkdirs();
			String fileName = String.valueOf(dataCollect.getId()) + nowDateStr
					+ ".txt";
			String path = String.valueOf(filePath) + fileName;
			if (dataCollect.getUploadUrl() != null
					&& dataCollect.getUploadUrl().trim().length() > 0) {

				path = dataCollect.getUploadUrl();
			}
			log.info("path:" + path);
			File file = new File(path);
			DataCollect bo = new DataCollect();
			bo.setId(dataCollect.getId());
			bo.setUploadUrl(path);
			dataMapper.updateDataById(bo);
			try {
				if (!file.exists())
					collectDataServiceImpl.createFile(path, data.toString());
				else
					collectDataServiceImpl.updateFile(path, data.toString());

			} catch (Exception e) {
				log.error("异常信息"+e.getMessage(),e);
			}
		}
		log.info("--定时从redis中读取视频数据写入磁盘文件结束--");

	}*/

	// @Scheduled(cron = "0 */1 * * * ?")
	public void uploadFileCollect() {
		log.info("--定时写入视频文件开始--");
		Set<String> keys = redisUtil.Keys("htmlvideo*");
		if (keys == null || keys.size() <= 0) {
			return;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		for (String key : keys) {
			Set<String> set = this.redisUtil.getZset(key);
			redisUtil.delete(key);// 删除redis缓存
			if (set == null || set.size() == 0) {
				continue;
			}
			log.info("视频定时保存key:" + key);
			String id = key.replace("htmlvideo", "");
			CollectHtmlVideo htmlVideo = collectHtmlVideoMapper.queryById(id);
			String nowDateStr = "";
			if (htmlVideo != null && htmlVideo.getUploadtime() != null) {
				nowDateStr = sdf.format(htmlVideo.getUploadtime());
			} else {
				nowDateStr = sdf.format(new Date());
			}
			Iterator<String> it = set.iterator();
			String str = "";
			StringBuffer data = new StringBuffer();
			String filePath = fileDir;
			while (it.hasNext()) {
				str = it.next();
				List<String> list1 = JSON.parseArray(str, String.class);
				for (String string : list1)
					data.append(string).append("\n");
			}
			filePath = String.valueOf(filePath) + nowDateStr.substring(0, 4)
					+ "/" + nowDateStr.substring(4, 6) + "/"
					+ nowDateStr.substring(6, 8) + "/"
					+ htmlVideo.getDatacollectId() + "/" + htmlVideo.getId()
					+ "/";
			File filep = new File(filePath);
			if (!filep.exists())
				filep.mkdirs();
			String fileName = String.valueOf(htmlVideo.getId()) + nowDateStr
					+ ".txt";
			String path = String.valueOf(filePath) + fileName;
			if (htmlVideo.getUploadUrl() != null
					&& htmlVideo.getUploadUrl().trim().length() > 0) {

				path = htmlVideo.getUploadUrl();
			}
			log.info("path:" + path);
			File file = new File(path);
			CollectHtmlVideo video = new CollectHtmlVideo();
			video.setId(id);
			video.setUploadUrl(path);
			collectHtmlVideoMapper.updateById(video);
			try {
				if (!file.exists())
					collectDataServiceImpl.createFile(path, data.toString());
				else
					collectDataServiceImpl.updateFile(path, data.toString());

			} catch (Exception e) {
				log.error(e);
			}
		}
		log.info("--定时写入视频文件结束--");
	}

//	@Scheduled(cron = "0 */5 * * * ?")
	public void updateFileCollect() {

		log.info("--定时从redis中读取视频数据写入磁盘文件开始--");
		Set<String> keys = redisUtil.Keys("v2"+"video*");
		if (keys == null || keys.size() <= 0) {
			log.info("--没有视频数据，定时器退出--");
			log.info("--定时从redis中读取视频数据写入磁盘文件结束--");
			return;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		for (String key : keys) {
			//若当前时间戳减去redis中存放的最大时间戳小于5分钟则不下载 begin
			Set<ZSetOperations.TypedTuple<String>> scoreSet = redisUtil.rangeWithScores(key);
			List<ZSetOperations.TypedTuple<String>> scorelist = new ArrayList<ZSetOperations.TypedTuple<String>>(scoreSet);
			ZSetOperations.TypedTuple<String> score = scorelist.get(scorelist.size()-1);
			//=======================修改5分钟bug添加的日志
			log.info("--5minutes--系统时间："+Calendar.getInstance().getTimeInMillis());
			log.info("--5minutes--score.getScore():"+score.getScore());
			log.info("--5minutes--时间差:"+(Calendar.getInstance().getTimeInMillis()-score.getScore()));
			log.info("--5minutes--if判断:"+((Calendar.getInstance().getTimeInMillis()-score.getScore())<5*60*1000));
			//=======================修改5分钟bug添加的日志
			if((Calendar.getInstance().getTimeInMillis()-score.getScore())<5*60*1000) continue;
			//若当前时间戳减去redis中存放的最大时间戳小于5分钟则不下载 end
			Set<String> set = this.redisUtil.getZset(key);
			redisUtil.delete(key);// 删除redis缓存
			if (set == null || set.size() == 0) {
				continue;
			}
			log.info("视频uuid: " + key);
			String id = key.replace("v2video", "");
			DataCollect dataCollect = dataCollectMapper.queryDataById(id);
			String nowDateStr = "";
			if (dataCollect != null && dataCollect.getUploadTime() != null) {
				nowDateStr = sdf.format(dataCollect.getUploadTime());
			} else {
				nowDateStr = sdf.format(new Date());
			}
			Iterator<String> it = set.iterator();
			String str = "";
			StringBuffer data = new StringBuffer();
			String filePath = fileDir;
			while (it.hasNext()) {
				str = it.next();
				List<String> list1 = JSON.parseArray(str, String.class);
				for (String string : list1)
					data.append(string).append("\n");
			}
			filePath = String.valueOf(filePath) + nowDateStr.substring(0, 4)
					+ "/" + nowDateStr.substring(4, 6) + "/"
					+ nowDateStr.substring(6, 8) + "/" + id
					+ "/";
			File filep = new File(filePath);
			if (!filep.exists())
				filep.mkdirs();
			String fileName = String.valueOf(id) + nowDateStr
					+ ".txt";
			String path = String.valueOf(filePath) + fileName;
			if (dataCollect.getUploadUrl() != null
					&& dataCollect.getUploadUrl().trim().length() > 0) {
				path = dataCollect.getUploadUrl();
			}
			log.info("path:" + path);
			File file = new File(path);
			DataCollect bo = new DataCollect();
			bo.setId(dataCollect.getId());
			bo.setUploadUrl(path);
			dataMapper.updateDataById(bo);
			try {
				if (!file.exists())
					collectDataServiceImpl.createFile(path, data.toString());
				else
					collectDataServiceImpl.updateFile(path, data.toString());

			} catch (Exception e) {
				log.error("异常信息"+e.getMessage(),e);
			}
		}
		log.info("--定时从redis中读取视频数据写入磁盘文件结束--");

	}
}